package edu.zju.gis.dbfg.server.util;

import edu.zju.gis.dbfg.server.model.ExternalDataArgs;
import edu.zju.gis.dbfg.server.model.vo.FeatureRecord;
import edu.zju.gis.dbfg.server.model.vo.tableRecordsWithTotalsize;
import org.json.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import java.sql.DriverManager;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class ApiHelper extends ExternalHelper {
    public JSONObject testConnection(ExternalDataArgs sourceConnect) throws Exception {
        String res = HttpClientUtil.sendHttpGet(sourceConnect.getUrl());
        JSONObject jsonObj = (JSONObject) (new JSONParser().parse(res));
        this.res = jsonObj;
        return this.res;
    }

    public List<JSONObject> queryConstruct(ExternalDataArgs sourceConnect) throws Exception {
        List<JSONObject> resObject = new ArrayList<>();
        return resObject;
    }

    public tableRecordsWithTotalsize pageSearh(ExternalDataArgs sourceConnect, int pageNo, int pageSize) throws Exception {
        tableRecordsWithTotalsize tableRecordsWithTotalsize = new tableRecordsWithTotalsize();
        String res = HttpClientUtil.sendHttpGet(sourceConnect.getUrl());
        JSONObject jsonObj = (JSONObject) (new JSONParser().parse(res));
        List<JSONObject> records = new ArrayList<>();
        Iterator<String> it = jsonObj.keySet().iterator();
        int count = 0;
        int start = (pageNo - 1) * pageSize;
        int end = pageNo * pageSize;
        while (it.hasNext()) {
            if (start <= count && count < end) {
                JSONObject jsonObject = new JSONObject();
                String key = it.next();
                Object value = jsonObj.get(key);
//            jsonObject.put(key, value);
                jsonObject.put("key", key);
                jsonObject.put("value", value.toString());
                records.add(jsonObject);
            } else {
                it.next();
            }
            count++;
        }
        tableRecordsWithTotalsize.setTotalSize(count);
        tableRecordsWithTotalsize.setRecords(records);
        return tableRecordsWithTotalsize;
    }

    public FeatureRecord identifyQuery(String lon, String lat, ExternalDataArgs sourceConnect) throws Exception {
        FeatureRecord featureRecord = new FeatureRecord();
        //根据sourceConnect得出坐标系
        //然后进行查询
        return featureRecord;
    }

    public List<FeatureRecord> areaQuery(JSONArray areaArray, ExternalDataArgs sourceConnect) throws Exception {
        //参数为前后闭合的polygon
        List<FeatureRecord> featureRecord = new ArrayList<>();
        return featureRecord;
    }
}

